package com.GlobalPaint.app.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.support.v4.util.LruCache;
import android.text.TextUtils;

import com.GlobalPaint.app.bean.LogBean;
import com.GlobalPaint.app.bean.ReturnStatusResultEntity;
import com.GlobalPaint.app.callback.JsonCallback;
import com.GlobalPaint.app.ui.Login.Login;
import com.blankj.utilcode.utils.EncryptUtils;
import com.blankj.utilcode.utils.SPUtils;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.request.BaseRequest;
import com.umeng.message.PushAgent;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/8/7.
 */
public class DataManager {
    public static Date isData;
    public static boolean messH;
    public interface Callback<T> {
        void onSuccess(T o);

        void onFailure(ReturnStatusResultEntity error);
    }

    private static DataManager inst = new DataManager();
    public static String DEFAULT_SAVE_IMAGE_PATH;
    public static DataManager getInst() {
        return inst;
    }

    //application的context
    public static Context context;
    //登录的token
    public static String deviceToken;//友盟设备token
    public static String baseUrl;//设置url
    public static String city;
    public static PushAgent mPushAgent;//友盟推送
    //用户信息
    public static LogBean.DataBean userEntity=new LogBean.DataBean();
    public static List<Activity> activityList = new LinkedList<Activity>();
    public static int typeId;
    public static String typename;
    public static LruCache<String, ArrayList> lruCache = new LruCache<>(10);
    /**
     * http的post提交方式
     *
     * @param url
     * @param token
     * @param data
     * @param Class
     * @param callback
     * @param <T>
     */
    public <T> void postHttpRequestJsonClass(String url, String token, Object data, final Class<T> Class, final Callback callback) {
        if (TextUtils.isEmpty(token)) {
            ReturnStatusResultEntity returnStatusResultEntity = new ReturnStatusResultEntity();
            returnStatusResultEntity.httpCode = Constants.PARAM_ERROR;
            returnStatusResultEntity.msg = "token不能为空";
            returnStatusResultEntity.isError = true;
            callback.onFailure(returnStatusResultEntity);
        }

        String timestamp = String.valueOf(System.currentTimeMillis());
        String jsonStr = new Gson().toJson(data);
      /*  try {
            jsonStr = URLEncoder.encode(jsonStr, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/
        String content = token + timestamp + url + jsonStr;
        String sign = EncryptUtils.encryptMD5ToString(content).toLowerCase();
        OkHttpUtils.post(url)     // 请求方式和请求url
                .headers("token", token)
                .headers("timestamp", timestamp)
                .headers("source", Constants.source)
                .headers("ver", Constants.ver)
                .headers("sign", sign)
                .headers("source", Constants.source)
                .upJson(jsonStr)
                .execute(new PangXieCallback<>(Class, callback));
    }
    public <T> void postHttpRequesFileClass(String url, String token, File file, final Class<T> Class, final Callback callback) {
        if (TextUtils.isEmpty(token)) {
            ReturnStatusResultEntity returnStatusResultEntity = new ReturnStatusResultEntity();
            returnStatusResultEntity.httpCode = Constants.PARAM_ERROR;
            returnStatusResultEntity.msg = "token不能为空";
            returnStatusResultEntity.isError = true;
            callback.onFailure(returnStatusResultEntity);
        }

        String timestamp = String.valueOf(System.currentTimeMillis());
//        String jsonStr = new Gson().toJson(data);
      /*  try {
            jsonStr = URLEncoder.encode(jsonStr, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/
//        String content = token + timestamp + url + jsonStr;
//        String sign = EncryptUtils.encryptMD5ToString(content).toLowerCase();
        OkHttpUtils.post(url)     // 请求方式和请求url
                .headers("token", token)
                .headers("timestamp", timestamp)
                .headers("source", Constants.source)
                .params("file",file)
                .execute(new PangXieCallback<>(Class, callback));
    }
    //多个文件
    public <T> void postHttpRequesFileSClass(String url, String token, List<File> files,final Class<T> Class, final Callback callback) {
        if (TextUtils.isEmpty(token)) {
            ReturnStatusResultEntity returnStatusResultEntity = new ReturnStatusResultEntity();
            returnStatusResultEntity.httpCode = Constants.PARAM_ERROR;
            returnStatusResultEntity.msg = "token不能为空";
            returnStatusResultEntity.isError = true;
            callback.onFailure(returnStatusResultEntity);
        }

        String timestamp = String.valueOf(System.currentTimeMillis());
        OkHttpUtils.post(url)     // 请求方filelisturl
                .addFileParams("file",files)
                .headers("token", token)
                .headers("timestamp", timestamp)
                .headers("source", Constants.source)
                .execute(new PangXieCallback<>(Class, callback));
    }
    public <T> void postHttpRequesPostClass(String url, String token, String fGender,String fBio,String fQq,String fWeixin,String fNickName,String company, final Class<T> Class, final Callback callback) {
        if (TextUtils.isEmpty(token)) {
            ReturnStatusResultEntity returnStatusResultEntity = new ReturnStatusResultEntity();
            returnStatusResultEntity.httpCode = Constants.PARAM_ERROR;
            returnStatusResultEntity.msg = "token不能为空";
            returnStatusResultEntity.isError = true;
            callback.onFailure(returnStatusResultEntity);
        }

        String timestamp = String.valueOf(System.currentTimeMillis());
        OkHttpUtils.post(url)     // 请求方式和请求url
                .headers("token", token)
                .headers("timestamp", timestamp)
                .headers("source", Constants.source)
                .params("fGender","")
                .params("fBio","")
                .params("fQq","")
                .params("fWeixin","")
                .params("fNickName","")
                .params("company","")
                .execute(new PangXieCallback<>(Class, callback));
    }



    public <T> void postHttpRequestJsonType(String url, String token, Object data, final Type type, final Callback callback) {
        if (TextUtils.isEmpty(token)) {
            ReturnStatusResultEntity returnStatusResultEntity = new ReturnStatusResultEntity();
            returnStatusResultEntity.httpCode = Constants.PARAM_ERROR;
            returnStatusResultEntity.msg = "token不能为空";
            returnStatusResultEntity.isError = true;
            callback.onFailure(returnStatusResultEntity);
        }

        String timestamp = String.valueOf(System.currentTimeMillis());
        String jsonStr = new Gson().toJson(data);
        /*try {
            jsonStr = URLEncoder.encode(jsonStr, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/
        String content = token + timestamp + url + jsonStr;
        String sign = EncryptUtils.encryptMD5ToString(content).toLowerCase();
        OkHttpUtils.post(url)     // 请求方式和请求url
                .headers("token", token)
                .headers("timestamp", timestamp)
                .headers("source", Constants.source)
                .headers("ver", Constants.ver)
                .headers("sign", sign)
                .upJson(jsonStr)
                .execute(new PangXieCallback<>(type, callback));
    }

    /**
     * http的delete请求方式
     *
     * @param url
     * @param token
     * @param Class
     * @param callback
     * @param <T>
     */
    public <T> void deleteHttpRequestJsonClass(String url, String token, final Class<T> Class, final Callback callback) {
        if (TextUtils.isEmpty(token)) {
            ReturnStatusResultEntity returnStatusResultEntity = new ReturnStatusResultEntity();
            returnStatusResultEntity.httpCode = Constants.PARAM_ERROR;
            returnStatusResultEntity.msg = "token不能为空";
            returnStatusResultEntity.isError = true;
            callback.onFailure(returnStatusResultEntity);
        }
        String timestamp = String.valueOf(System.currentTimeMillis());
        String content = token + timestamp + url;
        String sign = EncryptUtils.encryptMD5ToString(content).toLowerCase();
        OkHttpUtils.delete(url)     // 请求方式和请求url
                .headers("token", token)
                .headers("timestamp", timestamp)
                .headers("source", Constants.source)
                .headers("ver", Constants.ver)
                .headers("sign", sign)
                .execute(new PangXieCallback<>(Class, callback));

    }

    public <T> void deleteHttpRequestJsonType(String url, String token, final Type type, final Callback callback) {
        if (TextUtils.isEmpty(token)) {
            ReturnStatusResultEntity returnStatusResultEntity = new ReturnStatusResultEntity();
            returnStatusResultEntity.httpCode = Constants.PARAM_ERROR;
            returnStatusResultEntity.msg = "token不能为空";
            returnStatusResultEntity.isError = true;
            callback.onFailure(returnStatusResultEntity);
        }
        String timestamp = String.valueOf(System.currentTimeMillis());
        String content = token + timestamp + url;
        String sign = EncryptUtils.encryptMD5ToString(content).toLowerCase();
        OkHttpUtils.delete(url)     // 请求方式和请求url
                .headers("token", token)
                .headers("timestamp", timestamp)
                .headers("source", Constants.source)
                .headers("ver", Constants.ver)
                .headers("sign", sign)
                .execute(new PangXieCallback<>(type, callback));
    }

    /**
     * http的put请求方式，返还执行结果
     *
     * @param url
     * @param token
     * @param Class
     * @param callback
     * @param <T>
     */
    public <T> void putHttpRequestJsonClass(String url, String token, final Class<T> Class, final Callback callback) {
        if (TextUtils.isEmpty(token)) {
            ReturnStatusResultEntity returnStatusResultEntity = new ReturnStatusResultEntity();
            returnStatusResultEntity.httpCode = Constants.PARAM_ERROR;
            returnStatusResultEntity.msg = "token不能为空";
            returnStatusResultEntity.isError = true;
            callback.onFailure(returnStatusResultEntity);
        }
        String timestamp = String.valueOf(System.currentTimeMillis());
        String content = token + timestamp + url;
        String sign = EncryptUtils.encryptMD5ToString(content).toLowerCase();
        OkHttpUtils.put(url)     // 请求方式和请求url
                .headers("token", token)
                .headers("timestamp", timestamp)
                .headers("source", Constants.source)
                .headers("ver", Constants.ver)
                .headers("sign", sign)
                .execute(new PangXieCallback<>(Class, callback));
    }

    /**
     * http的put请求方式，参数中有json数据
     *
     * @param url
     * @param token
     * @param data
     * @param Class
     * @param callback
     * @param <T>
     */
    public <T> void putHttpRequestJsonClass(String url, String token, Object data, final Class<T> Class, final Callback callback) {
        if (TextUtils.isEmpty(token)) {
            ReturnStatusResultEntity returnStatusResultEntity = new ReturnStatusResultEntity();
            returnStatusResultEntity.httpCode = Constants.PARAM_ERROR;
            returnStatusResultEntity.msg = "token不能为空";
            returnStatusResultEntity.isError = true;
            callback.onFailure(returnStatusResultEntity);
        }

        String timestamp = String.valueOf(System.currentTimeMillis());
        String jsonStr = new Gson().toJson(data);
       /* try {
            jsonStr = URLEncoder.encode(jsonStr, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/
        String content = token + timestamp + url + jsonStr;
        String sign = EncryptUtils.encryptMD5ToString(content).toLowerCase();
        OkHttpUtils.put(url)     // 请求方式和请求url
                .headers("token", token)
                .headers("timestamp", timestamp)
                .headers("source", Constants.source)
                .headers("ver", Constants.ver)
                .headers("sign", sign)
                .upJson(jsonStr)
                .execute(new PangXieCallback<>(Class, callback));
    }

    public <T> void putHttpRequestJsonType(String url, String token, Object data, final Type type, final Callback callback) {
        if (TextUtils.isEmpty(token)) {
            ReturnStatusResultEntity returnStatusResultEntity = new ReturnStatusResultEntity();
            returnStatusResultEntity.httpCode = Constants.PARAM_ERROR;
            returnStatusResultEntity.msg = "token不能为空";
            returnStatusResultEntity.isError = true;
            callback.onFailure(returnStatusResultEntity);
        }

        String timestamp = String.valueOf(System.currentTimeMillis());
        String jsonStr = new Gson().toJson(data);
       /* try {
            jsonStr = URLEncoder.encode(jsonStr, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }*/
        String content = token + timestamp + url + jsonStr;
        String sign = EncryptUtils.encryptMD5ToString(content).toLowerCase();
        OkHttpUtils.put(url)     // 请求方式和请求url
                .headers("token", token)
                .headers("timestamp", timestamp)
                .headers("source", Constants.source)
                .headers("ver", Constants.ver)
                .headers("sign", sign)
                .upJson(jsonStr)
                .execute(new PangXieCallback<>(type, callback));
    }

    /**
     * http的get方式，返回执行结果
     *
     * @param url
     * @param token
     * @param Class
     * @param callback
     * @param <T>
     */
    public <T> void getHttpRequestJsonClass(String url, String token, final Class<T> Class, final Callback callback) {
        if (TextUtils.isEmpty(token)) {
            ReturnStatusResultEntity returnStatusResultEntity = new ReturnStatusResultEntity();
            returnStatusResultEntity.httpCode = Constants.PARAM_ERROR;
            returnStatusResultEntity.msg = "token不能为空";
            returnStatusResultEntity.isError = true;
            callback.onFailure(returnStatusResultEntity);
        }
        String timestamp = String.valueOf(System.currentTimeMillis());
        String content = token + timestamp + url;
        String sign = EncryptUtils.encryptMD5ToString(content).toLowerCase();
        OkHttpUtils.get(url)     // 请求方式和请求url
                .headers("token", token)
                .headers("timestamp", timestamp)
                .headers("source", Constants.source)
                .headers("ver", Constants.ver)
                .headers("sign", sign)
                .execute(new PangXieCallback<>(Class, callback));
    }

    /**
     * http的get方式，返回list
     *
     * @param url
     * @param token
     * @param type
     * @param callback
     * @param <T>
     */
    public <T> void getHttpRequestJsonType(String url, String token, final Type type, final Callback callback) {
        if (TextUtils.isEmpty(token)) {
            ReturnStatusResultEntity returnStatusResultEntity = new ReturnStatusResultEntity();
            returnStatusResultEntity.httpCode = Constants.PARAM_ERROR;
            returnStatusResultEntity.msg = "token不能为空";
            returnStatusResultEntity.isError = true;
            callback.onFailure(returnStatusResultEntity);
        }
        String timestamp = String.valueOf(System.currentTimeMillis());
        String content = token + timestamp + url;
        String sign = EncryptUtils.encryptMD5ToString(content).toLowerCase();
        OkHttpUtils.get(url)     // 请求方式和请求url
                .headers("token", token)
                .headers("timestamp", timestamp)
                .headers("source", Constants.source)
                .headers("ver", Constants.ver)
                .headers("sign", sign)
                .execute(new PangXieCallback<>(type, callback));
    }

    private <T> void handleResponse(T s, Call call, Response response, Callback<T> callback) {
        ReturnStatusResultEntity returnStatusResultEntity = CommUtility.getHttpStatusResult(response.code());
        if (!returnStatusResultEntity.isError) {
            callback.onSuccess(s);
        } else if (returnStatusResultEntity.httpCode == 403) {
            Intent intent = new Intent(DataManager.context, Login.class);

            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            DataManager.context.startActivity(intent);
        } else {
            callback.onFailure(returnStatusResultEntity);
        }
    }

    private <T> void handleError(Call call, @Nullable Response response, @Nullable Exception e, Callback<T> callback) {
        ReturnStatusResultEntity returnStatusResultEntity = new ReturnStatusResultEntity();
        if (response == null) {
            returnStatusResultEntity.isError = true;
            returnStatusResultEntity.msg = "请检查网络";
            returnStatusResultEntity.httpCode = Constants.NETWORK_ERROR;//网络异常错误
            callback.onFailure(returnStatusResultEntity);
        } else {

            ReturnStatusResultEntity httpStatusResult = CommUtility.getHttpStatusResult(response.code());
            if (!httpStatusResult.isError) {

            } else {

                if (httpStatusResult.httpCode == 403) {
                    if (userEntity != null)/*已经登录成功*/ {
                        SPUtils spUtils = new SPUtils(DataManager.context, "login");
                        spUtils.remove("token");
                        AppManager.getAppManager().finishAllActivity();
                        Intent intent = new Intent(DataManager.context, Login.class);
                        Login.loginFailed = true;
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        DataManager.context.startActivity(intent);
                    } else {
                        callback.onFailure(httpStatusResult);
                    }
                } else {
                    callback.onFailure(httpStatusResult);
                }
            }
        }
    }

    private class PangXieCallback<T> extends JsonCallback<T> {
        private Callback<T> callback;

        @Override
        public void onBefore(BaseRequest request) {
            super.onBefore(request);
        }

        @Override
        public void onAfter(@Nullable T t, @Nullable Exception e) {
            super.onAfter(t, e);
        }

        public PangXieCallback(Class<T> clazz, Callback<T> callback) {
            super(clazz);
            this.callback = callback;
        }

        public PangXieCallback(Type type, Callback<T> callback) {
            super(type);
            this.callback = callback;
        }

        @Override
        public void onSuccess(T t, Call call, Response response) {
            handleResponse(t, call, response, callback);
        }

        @Override
        public void onError(Call call, @Nullable Response response, @Nullable Exception e) {
            super.onError(call, response, e);
            handleError(call, response, e, callback);
        }
    }
}
